import os
from functools import total_ordering

from core.report import *
from core.adbConnect import *

from core.utils.file_utils import *
from core.utils.data_utils import *
from core.utils.logger_utils import *

class App:
    def __init__(self):

        self.current_path = get_current_file_path()
        config_path = self.current_path + r'/config/data.yaml'
        adb_path = self.current_path + r'/config/config.yaml'

        data = load_yaml(config_path)
        adb_config = load_yaml(adb_path)

        logger.info('设备初始化中')
        self.adb = AdbDevices(adb_config, logger)
        self.report = Report()
        logger.info('初始化完成')

        self.data = get_config_path(self.current_path, data)

        self.test_resource_path = self.data['ResourcePath']
        self.test_source_file = walk_source_dir(self.test_resource_path)

        self.photo_path = self.data['PhotoFolder']
        self.photo_file = walk_source_dir(self.photo_path)

        # 保存报告的路径
        self.report_path = self.data['ReportPath']

        # 获取apk列表用的是os.walk ,数据已经进行处理， [0]是单个apk， [1：]是split_apk
        test_apk_list_path = self.data['TestApkPath']
        self.test_apk_list = walk_apk_dir(test_apk_list_path)
        logger.info('本地测试软件列表装载完毕')

        other_apk_list_path = self.data['OtherApkPath']
        self.other_apk_list = walk_apk_dir(other_apk_list_path)
        logger.info('本地其他软件列表装载完毕')

        online_apk_package_list = paste_path(self.current_path,self.data['OnlineApkList'])
        with open(online_apk_package_list, 'r', encoding='utf-8') as f:
            self.online_apk_package_list = [line.rstrip('\n') for line in f]
        f.close()

        logger.info('在线软件列表装载完毕')
        # logger.info(self.online_apk_package_list)

    def install_online_apk(self, prograss, stauts, total_prograss, count):
        """
        安装在线apk
        :return:
        """
        count = self.adb.install_online_apk(self.online_apk_package_list, self.report, prograss, stauts, total_prograss, count)
        return count

    def update_apk(self, prograss, stauts):
        """
        更新apk
        :return:
        """
        self.adb.update_apk(self.report, logger)

    def install_test_apk(self, prograss, stauts):
        """
        安装需要用在测试的apk, 并进行report
        :return:
        """

        test_single_apk_list = self.test_apk_list[0]
        test_multi_apk_list = self.test_apk_list[1:]

        for apk in test_single_apk_list:
            try:
                res = self.adb.install_single_apk(apk)
                res = get_apk_single_name(res)
                self.report.add_record(res)
                logger.info(f"测试软件：{res['Apk']},安装完成")
                stauts.setText(f"({self.count} / {self.total_prograss}) 测试软件：{res['Apk']},安装完成")
            except Exception as e:
                logger.error(f"{apk}安装失败, {e}")
                stauts.setText(f"({self.count} / {self.total_prograss}) 测试软件：{res['Apk']},安装失败")
            prograss.setValue(10 + int(80 * (self.count / self.total_prograss)))
            self.count += 1

        for apk_list in test_multi_apk_list:
            try:
                res = self.adb.install_multiple_apk(apk_list)
                res = get_apk_multi_name(res)
                self.report.add_record(res)
                logger.info(f"测试软件：{res['Apk']},安装完成")
                stauts.setText(f"({self.count} / {self.total_prograss}) 测试软件：{res['Apk']},安装完成")
            except Exception as e:
                logger.error(f"{apk_list}安装失败, {e}")
                stauts.setText(f"({self.count} / {self.total_prograss}) 测试软件：{res['Apk']},安装失败")
            prograss.setValue(10 + int(80 * (self.count / self.total_prograss)))
            self.count += 1

    def install_other_apk(self, prograss, stauts):
        """
        安装其他apk, 并进行report
        :return:
        """

        other_single_apk_list = self.other_apk_list[0]
        other_multi_apk_list = self.other_apk_list[1:]

        for apk in other_single_apk_list:
            try:
                res = self.adb.install_single_apk(apk)
                res = get_apk_single_name(res)
                self.report.add_record(res)
                logger.info(f"其他软件：{res['Apk']},安装完成")
                stauts.setText(f"({self.count} / {self.total_prograss}) 其他软件：{res['Apk']},安装完成")
            except Exception as e:
                logger.error(f"{apk}安装失败, {e}")
                stauts.setText(f"({self.count} / {self.total_prograss}) 测试软件：{res['Apk']},安装失败")
            prograss.setValue(10 + int(80 * (self.count / self.total_prograss)))
            self.count += 1

        for apk_list in other_multi_apk_list:
            try:
                res = self.adb.install_multiple_apk(apk_list)
                res = get_apk_multi_name(res)
                self.report.add_record(res)
                logger.info(f"其他软件：{res['Apk']},安装完成")
                stauts.setText(f"({self.count} / {self.total_prograss}) 其他软件：{res['Apk']},安装完成")
            except Exception as e:
                logger.error(f"{apk_list}安装失败, {e}")
                stauts.setText(f"({self.count} / {self.total_prograss}) 测试软件：{res['Apk']},安装失败")
            prograss.setValue(10 + int(80 * (self.count / self.total_prograss)))
            self.count += 1

    def run(self, deivce_id=None, prograss_bar=None, stauts_bar=None):
        """
        运行整个程序
        :return:
        """

        # 连接设备
        if self.adb:
            pass
        else:
            prograss_bar.setValue(0)
            stauts_bar.setText('设备连接失败')
            logger.error('设备连接失败')
            return

        self.adb.set_device(deivce_id)
        prograss_bar.setValue(10)
        stauts_bar.setText('设备连接成功')

        # push 起始资源文件
        # print(self.photo_file)
        # print(self.test_source_file)

        self.adb.make_photo_dir()
        stauts_bar.setText(f'创建图片目录')
        self.adb.make_test_dir()

        for photo_file in self.photo_file:
            stauts_bar.setText(f'开始推送照片文件：{photo_file}')
            logger.info(f"开始推送照片文件：{photo_file}")
            self.adb.push_photo_file(self.photo_path, photo_file)

        for test_file in self.test_source_file:
            stauts_bar.setText(f'开始推送测试文件：{test_file}')
            logger.info(f"开始推送测试文件：{test_file}")
            self.adb.push_test_file(self.test_resource_path, test_file)

        self.total_prograss = (
                         len(self.online_apk_package_list) +
                         len(self.test_apk_list) - 1 + len(self.test_apk_list[0]) +
                         len(self.other_apk_list) -1 + len(self.other_apk_list[0])
        )

        self.count = 1

        self.install_test_apk(prograss_bar, stauts_bar)

        self.count = self.install_online_apk(prograss_bar, stauts_bar, self.total_prograss, self.count)

        self.install_other_apk(prograss_bar, stauts_bar)

        prograss_bar.setValue(90)
        stauts_bar.setText('尝试更新软件')
        self.update_apk(prograss_bar, stauts_bar)

        prograss_bar.setValue(100)
        stauts_bar.setText('软件安装完成')
        self.report.create_report(self.report_path)

    def save_report(self):
        """手动保存报告"""
        try:
            self.report.create_report(self.report_path)
            return True, "报告保存成功"
        except Exception as e:
            return False, f"报告保存失败: {str(e)}"

    def __iter__(self):
        return iter(self.adb.return_device())

    def __call__(self):
        return self.adb.return_device()

# app = App()
# app.run()